package com.example.park_management.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.park_management.common.PageParam;
import com.example.park_management.common.Result;
import com.example.park_management.domain.Expenses;
import com.example.park_management.domain.ParkingSpaces;
import com.example.park_management.service.ExpensesService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;


@RestController
@RequestMapping("/expenses")
public class ExpensesController {

    @Resource
    ExpensesService expensesService;

    @PostMapping("/")
    public Result add(@RequestBody Expenses expenses) {
        try{
            if (StringUtils.isBlank(expenses.getExpenseType())) {
                return Result.fail("必填属性为空");
            }
            boolean save = expensesService.save(expenses);
            return save ? Result.success() : Result.fail();
        }
        catch (Exception e) {
            return Result.fail("输入格式异常！");
        }
    }

    @PutMapping("/")
    public Result update(@RequestBody Expenses expenses) {
        try{
            if (StringUtils.isBlank(expenses.getExpenseType())) {
                return Result.fail("必填属性为空");
            }
            boolean update = expensesService.updateById(expenses);
            return update ? Result.success() : Result.fail();
        }catch (Exception e) {
            return Result.fail("输入格式异常！");
        }
    }

    @DeleteMapping("/{expenseId}")
    public Result delete(@PathVariable Integer expenseId) {
        boolean remove = expensesService.removeById(expenseId);
        return remove ? Result.success() : Result.fail();
    }

    @PostMapping("/page")
    public Result page(@RequestBody PageParam<Expenses> pageParam) {
        Page<Expenses> expensesPage = new Page<>(pageParam.getPageNum(), pageParam.getPageSize());


        QueryWrapper<Expenses> expensesQueryWrapper = new QueryWrapper<>();
        if (pageParam.getData() != null){
            if (pageParam.getData().getExpenseType() != null && !pageParam.getData().getExpenseType().isEmpty()){
                expensesQueryWrapper.eq("expense_type", pageParam.getData().getExpenseType());
            }
            if (pageParam.getData().getStatus() != null && pageParam.getData().getStatus() != -1){
                expensesQueryWrapper.eq("status", pageParam.getData().getStatus());
            }
            if (pageParam.getData().getOwnersId() != null && pageParam.getData().getOwnersId() != -1){
                expensesQueryWrapper.eq("owners_id", pageParam.getData().getOwnersId());
            }
        }

        expensesService.page(expensesPage,expensesQueryWrapper);
        return Result.success(expensesPage.getRecords(), expensesPage.getTotal());
    }

}
